package ${package.Controller};

import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ${table.comment!} 前端控制器
 *
 * @author ${author}
 * @since ${date}
 */
@Slf4j
@Validated
@Api(tags = "${table.comment!}管理")
@RestController
@RequestMapping("<#if package.ModuleName?? && package.ModuleName != "">/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
</#if>

    @Autowired
    private ${table.serviceName} ${table.serviceName?uncap_first};

    /**
     * 分页查询${table.comment!}列表
     */
    @ApiOperation("分页查询${table.comment!}列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页码", defaultValue = "1", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页大小", defaultValue = "10", dataType = "int", paramType = "query")
    })
    @GetMapping("/page")
    public ResponseEntity<Map<String, Object>> page(
            @RequestParam(value = "current", defaultValue = "1") Integer current,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            ${entity} entity) {
        try {
            Page<${entity}> page = new Page<>(current, size);
            IPage<${entity}> pageResult = ${table.serviceName?uncap_first}.pageList(page, entity);
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", pageResult);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("分页查询${table.comment!}列表失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "查询失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 查询${table.comment!}列表
     */
    @ApiOperation("查询${table.comment!}列表")
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> list(${entity} entity) {
        try {
            List<${entity}> list = ${table.serviceName?uncap_first}.listByCondition(entity);
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", list);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询${table.comment!}列表失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "查询失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 根据ID查询${table.comment!}详情
     */
    @ApiOperation("根据ID查询${table.comment!}详情")
    @ApiImplicitParam(name = "id", value = "${table.comment!}ID", required = true, dataType = "long", paramType = "path")
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getById(@PathVariable @NotNull Long id) {
        try {
            ${entity} entity = ${table.serviceName?uncap_first}.getByIdWithDetails(id);
            
            Map<String, Object> result = new HashMap<>();
            if (entity != null) {
                result.put("code", 200);
                result.put("message", "查询成功");
                result.put("data", entity);
            } else {
                result.put("code", 404);
                result.put("message", "${table.comment!}不存在");
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询${table.comment!}详情失败，ID: {}", id, e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "查询失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 新增${table.comment!}
     */
    @ApiOperation("新增${table.comment!}")
    @PostMapping
    public ResponseEntity<Map<String, Object>> create(@RequestBody @Valid ${entity} entity) {
        try {
            boolean success = ${table.serviceName?uncap_first}.create(entity);
            
            Map<String, Object> result = new HashMap<>();
            if (success) {
                result.put("code", 200);
                result.put("message", "新增成功");
                result.put("data", entity);
            } else {
                result.put("code", 400);
                result.put("message", "新增失败");
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("新增${table.comment!}失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "新增失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 更新${table.comment!}
     */
    @ApiOperation("更新${table.comment!}")
    @ApiImplicitParam(name = "id", value = "${table.comment!}ID", required = true, dataType = "long", paramType = "path")
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> update(@PathVariable @NotNull Long id, @RequestBody @Valid ${entity} entity) {
        try {
            entity.<#list table.fields as field><#if field.keyFlag>set${field.capitalName}(id)</#if></#list>;
            boolean success = ${table.serviceName?uncap_first}.update(entity);
            
            Map<String, Object> result = new HashMap<>();
            if (success) {
                result.put("code", 200);
                result.put("message", "更新成功");
                result.put("data", entity);
            } else {
                result.put("code", 400);
                result.put("message", "更新失败");
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("更新${table.comment!}失败，ID: {}", id, e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "更新失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 删除${table.comment!}
     */
    @ApiOperation("删除${table.comment!}")
    @ApiImplicitParam(name = "id", value = "${table.comment!}ID", required = true, dataType = "long", paramType = "path")
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> delete(@PathVariable @NotNull Long id) {
        try {
            boolean success = ${table.serviceName?uncap_first}.deleteById(id);
            
            Map<String, Object> result = new HashMap<>();
            if (success) {
                result.put("code", 200);
                result.put("message", "删除成功");
            } else {
                result.put("code", 400);
                result.put("message", "删除失败");
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("删除${table.comment!}失败，ID: {}", id, e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "删除失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 批量删除${table.comment!}
     */
    @ApiOperation("批量删除${table.comment!}")
    @DeleteMapping("/batch")
    public ResponseEntity<Map<String, Object>> deleteBatch(@RequestBody @Valid List<Long> ids) {
        try {
            boolean success = ${table.serviceName?uncap_first}.deleteBatchByIds(ids);
            
            Map<String, Object> result = new HashMap<>();
            if (success) {
                result.put("code", 200);
                result.put("message", "批量删除成功");
            } else {
                result.put("code", 400);
                result.put("message", "批量删除失败");
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("批量删除${table.comment!}失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "批量删除失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 批量新增${table.comment!}
     */
    @ApiOperation("批量新增${table.comment!}")
    @PostMapping("/batch")
    public ResponseEntity<Map<String, Object>> createBatch(@RequestBody @Valid List<${entity}> entityList) {
        try {
            boolean success = ${table.serviceName?uncap_first}.createBatch(entityList);
            
            Map<String, Object> result = new HashMap<>();
            if (success) {
                result.put("code", 200);
                result.put("message", "批量新增成功");
                result.put("data", entityList);
            } else {
                result.put("code", 400);
                result.put("message", "批量新增失败");
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("批量新增${table.comment!}失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "批量新增失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 统计${table.comment!}数量
     */
    @ApiOperation("统计${table.comment!}数量")
    @GetMapping("/count")
    public ResponseEntity<Map<String, Object>> count(${entity} entity) {
        try {
            long count = ${table.serviceName?uncap_first}.countByCondition(entity);
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "统计成功");
            result.put("data", count);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("统计${table.comment!}数量失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "统计失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 检查${table.comment!}是否存在
     */
    @ApiOperation("检查${table.comment!}是否存在")
    @GetMapping("/exists")
    public ResponseEntity<Map<String, Object>> exists(${entity} entity) {
        try {
            boolean exists = ${table.serviceName?uncap_first}.exists(entity);
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "检查成功");
            result.put("data", exists);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("检查${table.comment!}是否存在失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "检查失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
}
</#if>